package com.hiray.util

import android.content.Context
import android.net.Uri
import android.os.Build
import android.support.v4.content.FileProvider
import com.hiray.App
import com.hiray.BuildConfig
import java.io.File
import java.util.zip.ZipFile
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class AppHelper {


    companion object Helper {
        private const val TAG = "AppHelper"

        private const val INVITATION_TAG = "invitecode"

        lateinit var context: App

        private var inviteCode: String by sharePreference()

        fun init(context: App) {
            this.context = context
        }


        private fun sharePreference(): ReadWriteProperty<Helper, String> {
            return object : ReadWriteProperty<Helper, String> {
                override fun getValue(thisRef: Helper, property: KProperty<*>): String {
                    val sharePref = context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
                    return sharePref.getString("invitecode", "nullcode app is not installed by sharing")
                }

                override fun setValue(thisRef: Helper, property: KProperty<*>, value: String) {
                    val editor =
                            context.getSharedPreferences(BuildConfig.SHARE_FILE_NAME, Context.MODE_PRIVATE)
                                    .edit()
                    editor.putString("invitecode", value).apply()
                }
            }
        }

        /**
         * 读取邀请码
         */
        fun persistInvitationCode(context: Context): String? {
            val applicationInfo = context.applicationInfo
            val apkDir = applicationInfo.sourceDir
            val zipArchive = ZipFile(apkDir)
            val entries = zipArchive.entries()
            while (entries.hasMoreElements()) {
                val e = entries.nextElement()
                if (e.name != null && e.name.contains(INVITATION_TAG)) {
                    /*META-INF/invitecode_1a8h*/
                    inviteCode = e.name.substring(20)

                }
            }
            return inviteCode
        }


        fun fileUri(f: File): Uri {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return FileProvider.getUriForFile(context, "com.hiray.fileprovider", f)
            } else {
                return Uri.fromFile(f)
            }
        }

    }


}